//
//  BookDetailViewController.m
//  Learn
//
//  Created by 迟建国 on 2024/4/2.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "BookDetailViewController.h"
#import "BookChapterTableViewCell.h"
#import "ChapterDetailViewController.h"
#import "HomeRequest.h"
#import "TextbookDetailModel.h"
#import "WrittenExaminationController.h"

@interface BookDetailViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) TextbookDetailModel *model;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) UIImageView *bookImageView;
@property (nonatomic, strong) UILabel *nameL;
@property (nonatomic, strong) UILabel *messageL;

@property (nonatomic, strong) NSString *order;

@end

@implementation BookDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"书籍详情";
    self.view.backgroundColor = rgba(229, 229, 229, 1);
    [self setUI];
    [self loadData];
    // Do any additional setup after loading the view.
}

- (void)loadData {
    NSString *type = @"";
    if (self.type == BookTypeHearsay) {
        type = @"听说";
    } else if (self.type == BookTypeHearing) {
        type = @"听力";
    } else if (self.type == BookTypeFollowUpReading) {
        type = @"跟读";
    } else if (self.type == BookTypeWrittenExam) {
        type = @"笔试";
    } else if (self.type == BookTypePhonetic) {
        type = @"音标";
    } else if (self.type == BookTypeModelsp) {
        type = @"典范";
    } else if (self.type == BookTypeNewconcept) {
        type = @"新概念";
    } else if (self.type == BookTypeBlackplum) {
        type = @"黑布林";
    } else if (self.type == BookTypeInterest) {
        type = @"趣味";
    }
    [HomeRequest getTextbookDetailWithProductId:self.productId type:type result:^(TextbookDetailModel *model) {
        self.model = model;
        [self.bookImageView sd_setImageWithURL:[NSURL URLWithString:self.model.cover_full]];
        self.nameL.text = self.model.productName;
        self.messageL.text = [NSString stringWithFormat:@"适用于：%@",self.model.gradeName];
        [self.tableView reloadData];
        self.order = @"asc";
        [self loadBookChapterList];
    }];
}
- (void)loadBookChapterList
{ 
    NSString *type = @"";
    if (self.type == BookTypeHearsay) {
        type = @"听说";
    } else if (self.type == BookTypeHearing) {
        type = @"听力";
    } else if (self.type == BookTypeFollowUpReading) {
        type = @"跟读";
    } else if (self.type == BookTypeWrittenExam) {
        type = @"笔试";
    } else if (self.type == BookTypePhonetic) {
        type = @"音标";
    } else if (self.type == BookTypeModelsp) {
        type = @"典范";
    } else if (self.type == BookTypeNewconcept) {
        type = @"新概念";
    } else if (self.type == BookTypeBlackplum) {
        type = @"黑布林";
    } else if (self.type == BookTypeInterest) {
        type = @"趣味";
    }  else {
        
    }
    [HomeRequest getTextbookChapterListWithProductId:self.productId type:type order:self.order result:^(NSMutableArray *list) {
        self.dataArr = list;
        [self.tableView reloadData];
    }];
    
}
- (void)setUI {
    
    
    self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(0,lTopBarHeight, SCREEN_W, SCREEN_H - lTopBarHeight - SafeAreaBottomHeight) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    if (@available(iOS 13.0, *)) {
        [self.tableView setAutomaticallyAdjustsScrollIndicatorInsets:NO];
    } else {
        // Fallback on earlier versions
    }
    if (@available(iOS 15.0, *)) {
        self.tableView.sectionHeaderTopPadding = 0;
    } else {
        // Fallback on earlier versions
    }
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    self.tableView.backgroundColor=[UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    [self.tableView registerNib:[UINib nibWithNibName:@"BookChapterTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"BookChapterTableViewCell"];
    UIView *bookMessageView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 110)];
    bookMessageView.backgroundColor = UIColor.whiteColor;
    self.tableView.tableHeaderView = bookMessageView;
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 109, SCREEN_W, 0.5)];
    lineView.backgroundColor = rgba(229, 229, 229, 1);
    [bookMessageView addSubview:lineView];
    
    UIImageView *bookImageView = [[UIImageView alloc] init];
    [bookMessageView addSubview:bookImageView];
    self.bookImageView = bookImageView;
    [bookImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bookMessageView.mas_left).offset(10);
        make.top.equalTo(bookMessageView.mas_top).offset(10);
        make.width.offset(70);
        make.height.offset(84);
    }];
    
    UILabel *nameL = [[UILabel alloc] init];
    nameL.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:16];
    nameL.textColor = rgb(51, 51, 51);
    nameL.numberOfLines = 2;
    [bookMessageView addSubview:nameL];
    self.nameL = nameL;
    [nameL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bookImageView.mas_right).offset(15);
        make.top.equalTo(bookImageView.mas_top).offset(10);
        make.right.equalTo(bookMessageView.mas_right).offset(-10);
    }];
    
    UILabel *messageL = [[UILabel alloc] init];
    messageL.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:14];
    messageL.textColor = rgba(142, 142, 142, 1);
    messageL.numberOfLines = 2;
    [bookMessageView addSubview:messageL];
    self.messageL = messageL;
    [messageL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bookImageView.mas_right).offset(15);
        make.top.equalTo(nameL.mas_bottom).offset(15);
        make.right.equalTo(bookMessageView.mas_right).offset(-10);
    }];
    
    if (self.type == BookTypeHearsay) {
        self.view.backgroundColor = lWhiteColor;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BookChapterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BookChapterTableViewCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"BookChapterTableViewCell" owner:self options:nil] lastObject];
    }
    cell.model = self.dataArr[indexPath.row];
    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    TextbookChapterModel *model = self.dataArr[indexPath.row];
        ChapterDetailViewController *vc = [[ChapterDetailViewController alloc] init];
        vc.productId = model.productId;
        vc.type = self.type;
        vc.chapterId = model.id;
        vc.chapterName = model.name;
        [self.navigationController pushViewController:vc animated:YES];
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 52;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 44)];
    headerView.backgroundColor = [UIColor whiteColor];
    
    UILabel *nameL = [[UILabel alloc] init];
    nameL.text = @"内容目录";
    nameL.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:16];
    nameL.textColor = rgb(51, 51, 51);
    [headerView addSubview:nameL];
    [nameL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headerView.mas_left).offset(10);
        make.top.equalTo(headerView.mas_top).offset(15);
    }];
    
    UILabel *messageL = [[UILabel alloc] init];
    messageL.textColor = rgb(142, 142, 142);
    if (self.model.packageinfo.length > 0) {
        NSString *hasChapter = [NSString stringWithFormat:@"已更新%lu个章节",(unsigned long)self.dataArr.count];
        
        NSString *allChapter = [NSString stringWithFormat:@"/共%lu章节",(unsigned long)self.dataArr.count];
        NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@",hasChapter,allChapter]];
        [att addAttribute:NSForegroundColorAttributeName value:rgba(12, 183, 108, 1) range:[att.string rangeOfString:hasChapter]];
        messageL.attributedText = att;
    }
   
    messageL.font = MFontWithSize(16);
   
    [headerView addSubview:messageL];
    [messageL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nameL.mas_right).offset(10);
        make.top.equalTo(headerView.mas_top).offset(15);
    }];
    
    UILabel *messageL1 = [[UILabel alloc] init];
    messageL1.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:16];
    messageL1.textColor = rgb(142, 142, 142);
    [headerView addSubview:messageL1];
    [messageL1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(messageL.mas_right).offset(0);
        make.top.equalTo(headerView.mas_top).offset(15);
    }];

    if (self.model.packageinfo) {
        NSArray *ary = [self.model.packageinfo componentsSeparatedByString:@":"];
        NSArray *countary = [ary.lastObject componentsSeparatedByString:@"'"];
        if (countary.count>2) {
            NSString *count = countary[1];
            messageL.text = [NSString stringWithFormat:@"已更新%lu个章节",(unsigned long)self.dataArr.count];
            messageL1.text = [NSString stringWithFormat:@"/共%@章节",count];
        }
    }

    UIButton *sortBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [sortBtn setImage:[UIImage imageNamed:@"ic_booklist"] forState:UIControlStateNormal];
    WeakSelf(self);
    [sortBtn bk_whenTapped:^{
       weakself.order =  [weakself.order isEqualToString:@"asc"]?@"desc":@"asc";
        [weakself loadBookChapterList];
    }];
    [headerView addSubview:sortBtn];
    [sortBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(headerView.mas_right);
        make.centerY.equalTo(nameL.mas_centerY);
        make.width.height.offset(36);
    }];
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44; // 设置区头高度
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sectionHeaderHeight = 44; //区头的高度
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}
- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataArr;
}
@end
